/**
 *
 * @authors lq (713813)
 * @date    2017-08-28
 * @version $1$
 */

var keyWord = window.location.search.split('keyword=')[1],
    totalNum = 0,
    curPage = 1,
    perPageNum = 10;
if (keyWord) {
    getSearchResult(keyWord, curPage);
}

function getSearchResult(keyWord, curPage) {
    var setUrl = '',
        aResult = '';
    if (keyWord === '') {
        return false;
    } else {
        setUrl = "/api/article/search?keyword=" + keyWord + "&pageNo=" + curPage;
    }
    $.ajax({
        url: setUrl,
        type: 'GET',
        dataType: "json",
        success: function(data) {
            totalNum = data.count;
            if (totalNum > 0) {
                $('.no-result').hide();
                $('.result-list').show();
                var news = {};
                for (var i = 0; i < data.rows.length; i++) {
                    news = data.rows[i];
                    var newsTitle = news.title,
                        newsTime = news.publish_time,
                        newsUrl = '/article/detail?articleId=' + news.id;
                    if (news.articleType && news.articleType.parent && news.articleType.parent.name == "华渔视界") {
                        newsUrl += "&video=1";
                    }
                    aResult += '<li>';
                    aResult += '<a href="' + newsUrl + '" title="' + newsTitle + '" target="_blank">' + newsTitle + '</a>';
                    aResult += '</li>';
                }
                $('.result-list').html(aResult); //将结果添加到容器元素中

                $('.page').pagination({
                    itemsTotal: totalNum,
                    perPageLen: perPageNum,
                    prevPageTxt: '«',
                    nextPageTxt: '»',
                    activeCls: 'cur',
                    defaultPage: curPage,
                    showInput: false,
                    onClick: function(curPage, size, total) {
                        getSearchResult(keyWord, curPage)
                    // loadList(curPage, size, total);
                    },
                });
            } else {
                $('.result-list').hide();
                $('.no-result').show();
            }
            $('.main-result').find('.count').text(totalNum);
        }
    });
}

//do search
$(function() {
    $('.btn-search').on('click', function() {
        var keyWord = $(this).siblings('input').val(),
            basePath = window.location.href.split('?keyword=')[0];
        if (keyWord) {
            if (basePath) {
                window.location.href = basePath + '?keyword=' + encodeURIComponent(keyWord);
            }
        }
    });
    $('.search-wrap input').on('keydown', function(e) {
        if ($(this).val() && e.keyCode === 13) {
            $('.btn-search').trigger('click');
        }
    });
    
    /*将搜索结果条数填入文字中*/
    var currUrl = window.location.href,
        strAfter = decodeURI(currUrl.split('?keyword=', 2)[1]);
    $('.main-result').find('.keyword').text(strAfter);
})
